#!/usr/bin/env python3
"""
部署检查脚本
检查所有依赖、配置和路径是否正确
"""

import os
import sys
import subprocess
import importlib
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    print("🐍 检查Python版本...")
    version = sys.version_info
    if version.major >= 3 and version.minor >= 9:
        print(f"✅ Python版本: {version.major}.{version.minor}.{version.micro}")
        return True
    else:
        print(f"❌ Python版本过低: {version.major}.{version.minor}.{version.micro} (需要 >= 3.9)")
        return False

def check_requirements():
    """检查requirements.txt中的依赖"""
    print("\n📦 检查Python依赖...")
    
    requirements_file = Path(__file__).parent / 'requirements.txt'
    if not requirements_file.exists():
        print("❌ requirements.txt文件不存在")
        return False
    
    missing_packages = []
    with open(requirements_file, 'r') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#'):
                package_name = line.split('==')[0].split('>=')[0].split('<=')[0]
                try:
                    importlib.import_module(package_name.replace('-', '_'))
                    print(f"✅ {package_name}")
                except ImportError:
                    print(f"❌ {package_name} - 未安装")
                    missing_packages.append(line)
    
    if missing_packages:
        print(f"\n❌ 缺少 {len(missing_packages)} 个依赖包:")
        for pkg in missing_packages:
            print(f"   - {pkg}")
        print("\n安装命令:")
        print("pip install -r requirements.txt")
        return False
    else:
        print("✅ 所有Python依赖已安装")
        return True

def check_django_setup():
    """检查Django配置"""
    print("\n🎯 检查Django配置...")
    
    try:
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devops.settings')
        import django
        django.setup()
        print("✅ Django配置正确")
        return True
    except Exception as e:
        print(f"❌ Django配置错误: {e}")
        return False

def check_database():
    """检查数据库"""
    print("\n🗄️ 检查数据库...")
    
    try:
        from django.db import connection
        cursor = connection.cursor()
        cursor.execute("SELECT 1")
        print("✅ 数据库连接正常")
        
        # 检查迁移状态
        from django.core.management import execute_from_command_line
        print("检查迁移状态...")
        # 这里不直接执行，只是检查是否可以导入
        print("✅ 数据库迁移工具可用")
        return True
    except Exception as e:
        print(f"❌ 数据库问题: {e}")
        return False

def check_paths():
    """检查路径配置"""
    print("\n📁 检查路径配置...")
    
    # 检查项目结构
    base_dir = Path(__file__).parent
    project_root = base_dir.parent
    
    required_paths = [
        base_dir / 'logs',
        base_dir / 'media',
        base_dir / 'static',
        project_root / 'devops-frontend',
    ]
    
    all_good = True
    for path in required_paths:
        if path.exists():
            print(f"✅ {path}")
        else:
            print(f"❌ {path} - 不存在")
            all_good = False
    
    # 检查settings中的路径配置
    try:
        from django.conf import settings
        print(f"✅ BASE_DIR: {settings.BASE_DIR}")
        print(f"✅ MEDIA_ROOT: {settings.MEDIA_ROOT}")
        print(f"✅ STATIC_ROOT: {settings.STATIC_ROOT}")
        
        if hasattr(settings, 'FRONTEND_PATH'):
            print(f"✅ FRONTEND_PATH: {settings.FRONTEND_PATH}")
        
    except Exception as e:
        print(f"❌ 路径配置错误: {e}")
        all_good = False
    
    return all_good

def check_frontend():
    """检查前端项目"""
    print("\n🎨 检查前端项目...")
    
    project_root = Path(__file__).parent.parent
    frontend_path = project_root / 'devops-frontend'
    
    if not frontend_path.exists():
        print(f"❌ 前端项目不存在: {frontend_path}")
        return False
    
    package_json = frontend_path / 'package.json'
    if not package_json.exists():
        print("❌ package.json不存在")
        return False
    
    node_modules = frontend_path / 'node_modules'
    if not node_modules.exists():
        print("❌ node_modules不存在，需要运行: npm install")
        return False
    
    print("✅ 前端项目结构正常")
    return True

def create_missing_directories():
    """创建缺失的目录"""
    print("\n📂 创建必要的目录...")
    
    base_dir = Path(__file__).parent
    required_dirs = [
        base_dir / 'logs',
        base_dir / 'media',
        base_dir / 'media' / 'avatars',
        base_dir / 'static',
    ]
    
    for dir_path in required_dirs:
        if not dir_path.exists():
            dir_path.mkdir(parents=True, exist_ok=True)
            print(f"✅ 创建目录: {dir_path}")
        else:
            print(f"✅ 目录已存在: {dir_path}")

def main():
    """主检查函数"""
    print("🚀 DevOps系统部署检查")
    print("=" * 50)
    
    checks = [
        ("Python版本", check_python_version),
        ("Python依赖", check_requirements),
        ("Django配置", check_django_setup),
        ("数据库", check_database),
        ("路径配置", check_paths),
        ("前端项目", check_frontend),
    ]
    
    results = []
    for name, check_func in checks:
        try:
            result = check_func()
            results.append((name, result))
        except Exception as e:
            print(f"❌ {name}检查失败: {e}")
            results.append((name, False))
    
    # 创建缺失的目录
    create_missing_directories()
    
    # 总结
    print("\n" + "=" * 50)
    print("📊 检查结果总结:")
    
    passed = 0
    for name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"   {name}: {status}")
        if result:
            passed += 1
    
    print(f"\n通过: {passed}/{len(results)}")
    
    if passed == len(results):
        print("🎉 所有检查通过！系统可以部署")
        return True
    else:
        print("⚠️  存在问题，请修复后重新检查")
        return False

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
